//
//  YCNetWorkTools.swift
//  weiBoSwift
//
//  Created by 刘胤辰 on 16/7/23.
//  Copyright © 2016年 it.com. All rights reserved.
//

import UIKit
import AFNetworking

enum YCNetWorkType: String{
    
    case POST="POST"
    case GET="GET"
}

//路径
let filePath=((NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last)! as NSString).stringByAppendingPathComponent("userAccount.file")

class YCNetWorkTools: AFHTTPSessionManager {
    
    //创建全局访问点(单例)
    static var shareTools : YCNetWorkTools = {
        let tools = YCNetWorkTools()
            // 指定反序列化格式
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
    
    //封装afn
    func request(type:YCNetWorkType,urlstring:String,parameters:AnyObject?,success:(response : AnyObject?)->(),failure:(error:NSError)->()){
        
        if type == .GET {
            
            GET(urlstring, parameters: parameters, progress: nil, success: { (_, response) -> Void in
                    
                    success(response: response)
                }, failure: { (_, error) -> Void in
                    
                    failure(error: error)
            })
            
        }else{
            
            POST(urlstring, parameters: parameters, progress: nil, success: { (_, response) -> Void in
                    
                    success(response: response)
                }, failure: { (_, error) -> Void in
                    
                    failure(error: error)
            })
            
        }
    }
    

}



//MARK: 加载aouth界面的数据
extension YCNetWorkTools{
    
    func getOauthData(code:String,success:(response:AnyObject?)->(),falure:(error:NSError)->()){
        
        // 请求urlString
        let urlString = "https://api.weibo.com/oauth2/access_token"
        // 请求参数
        let params = [
            "client_id": APPKEY,
            "client_secret": APPSECRET,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": APPREDIRECT_URI
        ]
        request(YCNetWorkType.POST, urlstring: urlString, parameters: params, success: success, failure: falure)
    }
    
    //加载用户信息
    func loadUserInfoData(userAccount:SHUserAccount,success:(response:AnyObject?)->(),falure:(error:NSError)->()){
       
        // 请求的urlString
        let urlString = "https://api.weibo.com/2/users/show.json"
        // 请求参数
        let params = [
            "access_token": userAccount.access_token!,
            "uid": userAccount.uid!
        ]
        
        request(.GET, urlstring: urlString, parameters: params, success: success, failure: falure)
    }
    
}
